package cn.mengfly.fxtest.app.urltest;

import com.google.common.base.Strings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

/**
 * @author Mengfly
 */
public class UrlTestView extends StackPane {

    private final UrlTestViewModel testViewModel = new UrlTestViewModel();

    private final Label lblStatus = new Label();
    private final Label lblLoadTime = new Label();
    private final TextField tfUrl = new TextField();

    private final Label lblTaskStatus = new Label();
    private final ProgressBar pb = new ProgressBar();
    private final HBox statusHbox = new HBox(pb, lblTaskStatus);

    private final Button btnTest = new Button("Test");


    public UrlTestView() {
        Label lblUrl = new Label("Url to Test");

        HBox resultHbox = new HBox(lblStatus, lblLoadTime);
        resultHbox.setSpacing(10);

        VBox vBox = new VBox(lblUrl, tfUrl, btnTest, resultHbox);
        vBox.setPadding(new Insets(40));
        vBox.setSpacing(10);
        vBox.setAlignment(Pos.CENTER_LEFT);

        statusHbox.setSpacing(4);
        statusHbox.setPadding(new Insets(4));
        statusHbox.setMaxHeight(20);

        StackPane.setAlignment(statusHbox, Pos.BOTTOM_LEFT);
        this.getChildren().addAll(vBox, statusHbox);

        initListener();

        bindingModel();
    }

    private void initListener() {
        btnTest.setOnAction(event -> testViewModel.test());

        testViewModel.errorMessageProperty().addListener((observable, oldValue, newValue) -> {
            if (!Strings.isNullOrEmpty(newValue)) {
                Alert alert = new Alert(AlertType.ERROR, newValue);
                alert.showAndWait();
            }
        });
    }

    private void bindingModel() {
        lblStatus.textProperty().bind(testViewModel.statusCodeProperty());
        lblLoadTime.textProperty().bind(testViewModel.loadTimeProperty());
        testViewModel.urlProperty().bind(tfUrl.textProperty());

        statusHbox.visibleProperty().bind(testViewModel.urlTestTaskRunningProperty());
        pb.progressProperty().bind(testViewModel.urlTestTaskProgressProperty());
        lblTaskStatus.textProperty().bind(testViewModel.urlTestTaskMessageProperty());
    }
}
